//首页
'use strict';
import React, {Component} from 'react';
import HomeBanner from './homeBanner';//轮播广告
import HomeCategory from './homeCategory';//分类项目
import Util from '../common/util';
import * as URLconstant from '../constant/URLconstant'
import styles from '../style/styles';
import Toast from '../common/ToastUtil'
import News from '../news/newsList';
import {
    View,
    Text,
    ScrollView,
    TouchableOpacity,
    Image,
    DeviceEventEmitter,
    RefreshControl, Platform,
    TextInput,
    Alert
} from 'react-native';
import MyStroage from "../common/myStroage";
import CodePush from "react-native-code-push";

export default class HomeIndex extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            loaded: false,
            height: 0,
            again: false,
            isOver: false,
            page: 1,
            goods_cate_name_list: [],
            isRefreshing: false,
            cate_index: 1,
            imgHeightList: [],
            goodsData: [],
            isLogin: true,
            loadedGoods: false,

        };
        this.successCallback = this.successCallback.bind(this)
        this.topHeader = this.topHeader.bind(this)
        // this._onRefresh=this._onRefresh.bind(this)
    }


    async componentDidMount() {
        CodePush.sync();
        this.getCurrentTime()
        this.getindex()
        //DeviceEventEmitter.addListener('initQRCodeData', this.onOrderSuccess);
        DeviceEventEmitter.addListener("INDEXHOME", this.onOrderSuccess)
        DeviceEventEmitter.addListener("login", this.getUser.bind(this))
        DeviceEventEmitter.addListener("logout", this.getUser.bind(this))
        DeviceEventEmitter.addListener("buyGroup", this.getGroup.bind(this))
        this.getUser()
    }

    getCurrentTime() {
        let that = this
        this.getTimer = setInterval(function () {
            let timestamp = parseInt((new Date()).getTime() / 1000)
            that.setState({
                curTime: timestamp,
            })
        }, 1000)
    }

    componentWillUnmount() {
        this.getTimer && clearInterval(this.getTimer)
    }


    async getUser() {
        let userInfoDate = await MyStroage.getStorageAllDataForKey('userinfo')
        if (userInfoDate) {
            this.setState({
                isLogin: true,
                user_id: userInfoDate.data.user_id
            })
        } else {
            this.setState({
                isLogin: false
            })
        }
    }


    //二维码扫描回调的结果;
    onOrderSuccess(msg) {
        //Toast.show('你扫描啦我,我得到的结果=====' + msg);

    }


    getindex() {
        let datakey = [];
        let url = URLconstant.INDEX_HOME_URL;
        datakey['no_goods_cate'] = 1
        Util.get(url, datakey, this.successCallback, this.errorCallBack)
    }


    successCallback(datas) {
        //LOG('首页数据====' + JSON.stringify(datas))
        let dataIndex = datas.data;
        let cate_list = dataIndex.cate_list//商品分类;
        let ads_on = dataIndex.ads_on//轮播图片;
        let articl_list = dataIndex.articl_list//头条列表
        let nav_list = dataIndex.nav_list//导航
        this.setState({
            cate_list: cate_list,
            ads_on: ads_on,
            articl_list: articl_list,
            nav_list: nav_list,
            loaded: true,
            indexData: dataIndex,
            goods_cate_name_list: dataIndex.goods_cate_name_list,
            isRefreshing: false
        })
        this.getIndexGoods()
    }


    getIndexGoods() {
        let url = URLconstant.GET_INDEX_GOODS
        let datakey = []
        datakey['is_property'] = this.state.cate_index
        let user_id = this.state.user_id
        if (user_id) {
            datakey['user_id'] = user_id
        }
        Util.get(url, datakey, (datas) => {
            if (datas.status == 0) {
                this.setState({
                    goodsData: datas.data,
                    loadedGoods: true
                })
                this.getGoodsCateImg(datas.data)
            } else {
                this.setState({
                    goodsData: [],
                    loadedGoods: true
                })
            }
        }, () => {

        })
    }


    getGroup() {
        let url = URLconstant.GROUP_LIST
        let datakey = []
        let user_id = this.state.user_id
        if (user_id) {
            datakey['user_id'] = user_id
        }
        Util.get(url, datakey, (datas) => {
            let groupList = []
            if (datas.status == 0) {
                groupList = datas.data
            }
            this.setState({
                loadedGoods: true,
                groupList: groupList
            })
        }, (err) => {

        })
    }

    async getGoodsCateImg(urls) {
        let list = [];
        urls.map((item, index) => {
            Image.getSize(item.cate_list.ad_picture, (width, height) => {
                let imgheight = Util.size.width * height / width;
                list[index] = imgheight
                if (list.length == urls.length) {
                    this.setState({
                        imgHeightList: list,
                    })
                }
            }, (err) => {
                list[index] = 0
            })
        })
    }


    getGoodsByCateId() {
        let page = this.state.page
        let goods_cate_name_list = this.state.goods_cate_name_list
        if (goods_cate_name_list.length == 0) {
            return null
        }
        let datakey = []
        let url = URLconstant.GET_GOODS
        datakey['cid'] = goods_cate_name_list[page - 1].cate_id
        Util.get(url, datakey, this.getGoodsSuc.bind(this), this.errorCallBack.bind(this))
    }

    getGoodsSuc(datas) {
        if (datas.status == 0) {
            let page = this.state.page
            let goods_cate_name_list = this.state.goods_cate_name_list
            let isOver = false
            let again = true
            if (page == goods_cate_name_list.length) {
                isOver = true
                again = false
            }
            LOG('isOver====' + isOver, 'page====' + page, 'goods_cate_name_list.length===' + goods_cate_name_list.length)
            let newList = []
            newList[0] = datas.data
            let oldDatas = this.state.dataSource;
            Array.prototype.push.apply(oldDatas, newList);
            LOG('oldDatas====' + JSON.stringify(oldDatas))
            this.setState({
                isOver: isOver,
                dataSource2: this.state.dataSource2.cloneWithRows(oldDatas),
                dataSource: oldDatas,
                again: again,
            })
        }
    }


    errorCallBack(err) {
        LOG('err=======' + err)
    }

    layout(e) {
        LOG('e====' + JSON.stringify(e))
        let height = this.state.height
        if (e.layout.height > height) {
            this.setState({
                height: e.layout.height
            })
        }
    }


    topHeader() {
        let ads_on = this.state.ads_on//轮播图片;
        let nav_list = this.state.nav_list//导航
        return (
            <View>
                <HomeBanner navigation={this.props.navigation} dataindex={ads_on}/>
                <HomeCategory navigation={this.props.navigation} dataindex={nav_list} isLogin={this.state.isLogin}
                              toLogin={this.toLogin.bind(this)}/>
                {this.showCateNav()}
                {this.showCateGoods()}
            </View>
        )
    }

    //获取剩余时间
    getLastTime(end_time) {
        let curTime = this.state.curTime
        if (!curTime) {
            curTime = parseInt((new Date()).getTime() / 1000)
        }
        if (Number.isInteger(end_time) == false) {
            if (end_time.indexOf('-') != -1) {
                end_time = parseInt(new Date(end_time.replace(/-/g, '/')).getTime() / 1000)
            }
        }
        let lastTime = end_time - curTime
        let second = 0
        let minute = 0
        let hour = 0
        let day = 0
        if (lastTime > 60) {
            second = parseInt(lastTime % 60)
            minute = parseInt(lastTime / 60)
            if (minute > 60) {
                hour = parseInt(minute / 60)
                minute = parseInt(minute % 60)
                if (hour > 24) {
                    day = parseInt(hour / 24) //日
                    hour = parseInt(hour % 24) //时
                }
            }
        } else {
            second = lastTime
        }
        hour = hour > 0 ? (hour < 10 ? "0" + hour : hour) : '00'
        minute = minute > 0 ? (minute < 10 ? "0" + minute : minute) : '00'
        second = second > 0 ? (second < 10 ? "0" + second : second) : '00'
        return day > 0 ? day + '天' + hour + ":" + minute + ":" + second : hour + ":" + minute + ":" + second
    }


    showProgress(total, num) {
        let width = Util.size.width - 150
        let progress_width = width * (num / total)
        return (
            <View style={{width: width, height: 10, borderRadius: 5, backgroundColor: "#f2f2f2"}}>
                <View
                    style={{
                        height: 10,
                        borderRadius: 5,
                        width: progress_width,
                        backgroundColor: "#ee1f12",
                        position: "absolute",
                        top: 0,
                        left: 0
                    }}
                />
            </View>
        )
    }

    showCateGoods() {
        let imgList = this.state.imgHeightList
        let loadedGoods = this.state.loadedGoods
        if (!loadedGoods) {
            return (
                <View style={{width: Util.size.width, height: 30}}>
                    {Util.loading()}
                </View>
            )
        }
        let cate_index = this.state.cate_index
        if (cate_index == 4) {
            let groupList = this.state.groupList
            if (groupList.length == 0) {
                return (
                    <View style={{width: Util.size.width, paddingVertical: 50, alignItems: 'center'}}>
                        <Text style={{fontSize: 14, color: "#000"}}>平台没有设置拼团</Text>
                    </View>
                )
            }
            return (
                <View style={{paddingVertical: 10}}>
                    {
                        groupList.map((item, index) => {
                            return (
                                <TouchableOpacity
                                    onPress={() => this.toGroupGoodsIndex(item.id, item.goods_id)}
                                    key={index}
                                    style={{
                                        flexDirection: "row",
                                        paddingHorizontal: 10,
                                        paddingVertical: 5,
                                        borderBottomWidth: 1,
                                        borderBottomColor: "#f0f0f0"
                                    }}>
                                    <Image
                                        source={{uri: item.default_image}}
                                        resizeMode={'cover'}
                                        style={{width: 120, height: 120,}}
                                    />
                                    <View style={{
                                        height: 120,
                                        flex: 1,
                                        paddingLeft: 10,
                                        justifyContent: 'space-between'
                                    }}>
                                        <Text style={{fontSize: 14, color: "#000"}}
                                              numberOfLines={2}>{item.goods_name}</Text>
                                        <View style={{flexDirection: 'row', alignItems: 'center'}}>
                                            <Text style={{fontSize: 12, color: "#696969"}}>剩余</Text>
                                            <Text style={{
                                                fontSize: 12,
                                                color: "#ee1f12"
                                            }}> {this.getLastTime(item.end_time)} </Text>
                                            <Text style={{fontSize: 12, color: "#696969"}}>结束</Text>
                                        </View>
                                        {this.showProgress(item.tuan_quantity, item.buy_quantity)}
                                        <Text style={{
                                            fontSize: 12,
                                            color: "#696969"
                                        }}>{item.buy_quantity}件已拼,还差{item.tuan_quantity - item.buy_quantity}件</Text>
                                        <View style={{flexDirection: 'row', alignItems: 'center'}}>
                                            <View style={{flexDirection: 'row', alignItems: 'center', marginRight: 5}}>
                                                <Text style={{
                                                    fontSize: 12,
                                                    color: "#ee1f12",
                                                    marginTop: 5,
                                                    marginRight: 2
                                                }}>¥</Text>
                                                <Text style={{fontSize: 18, color: "#ee1f12"}}>{item.act_price}</Text>
                                            </View>
                                            <Text style={{
                                                fontSize: 12,
                                                color: "#969696",
                                                textDecorationLine: "line-through"
                                            }}>¥{item.price}</Text>
                                        </View>
                                    </View>
                                </TouchableOpacity>
                            )
                        })
                    }
                </View>
            )
        } else {
            let goodsData = this.state.goodsData
            if (goodsData.length == 0) {
                return (
                    <View style={{width: Util.size.width, paddingVertical: 50, alignItems: 'center'}}>
                        <Text style={{fontSize: 14, color: "#000"}}>没有商品</Text>
                    </View>
                )
            }
            return (
                <View>
                    {
                        goodsData.map((item, index) => {
                            return (
                                <View key={index}>
                                    {
                                        item.cate_list.ad_picture ?
                                            <Image
                                                source={{uri: item.cate_list.ad_picture}}
                                                style={{width: Util.size.width, height: imgList[index]}}
                                                resizeMode={'cover'}
                                            /> : null
                                    }
                                    <View style={{padding: 10, flexDirection: 'row', flexWrap: "wrap"}}>
                                        {
                                            item.goods_list.map((goods, index2) => {
                                                return (
                                                    <TouchableOpacity
                                                        onPress={() => this.toGoodsIndex(goods.goods_id)}
                                                        key={goods.goods_id}
                                                        style={[{
                                                            width: (Util.size.width - 40) / 3,
                                                            height: (Util.size.width - 40) / 3 + 50,
                                                            marginLeft: 10,
                                                        }, index2 % 3 == 0 ? {marginLeft: 0} : null]}>
                                                        <Image
                                                            source={{uri: goods.default_image}}
                                                            resizeMode={'cover'}
                                                            style={{
                                                                width: (Util.size.width - 40) / 3,
                                                                height: (Util.size.width - 40) / 3
                                                            }}
                                                        />
                                                        <View style={{
                                                            paddingHorizontal: 10,
                                                            justifyContent: 'space-around',
                                                            paddingVertical: 5
                                                        }}>
                                                            <Text numberOfLines={1} style={{
                                                                fontSize: 14,
                                                                color: "#333",
                                                                marginBottom: 2
                                                            }}>{goods.goods_name}</Text>
                                                            <Text style={{
                                                                fontSize: 12,
                                                                color: "#f00"
                                                            }}>{this.toFixNum(goods.buy_price)}/米</Text>
                                                        </View>
                                                    </TouchableOpacity>
                                                )
                                            })
                                        }
                                    </View>
                                </View>
                            )
                        })
                    }
                </View>
            )
        }

    }

    toFixNum(num) {
        return parseFloat(num).toFixed(2)
    }

    async selectCate(cate_index) {
        await this.setState({
            cate_index: cate_index,
            loadedGoods: false
        })
        if (cate_index == 4) {
            this.getGroup()
        } else {
            this.getIndexGoods()
        }
    }

    showCateNav() {
        return (
            <View style={{
                flexDirection: 'row',
                backgroundColor: "#f0f0f0",
                borderBottomWidth: 1,
                borderBottomColor: "#e0e0e0"
            }}>
                <TouchableOpacity
                    onPress={() => this.selectCate(1)}
                    style={[{flex: 1, alignItems: 'center', justifyContent: 'center', height: 40}]}>
                    <View style={[{
                        alignItems: 'center',
                        justifyContent: 'center',
                        height: 40
                    }, this.state.cate_index == 1 ? {
                        borderBottomWidth: 1,
                        borderBottomColor: "#ee1f12"
                    } : {borderBottomWidth: 2, borderBottomColor: "transparent"}]}>
                        <Text style={this.state.cate_index == 1 ? {fontSize: 14, color: "#ee1f12"} : {
                            fontSize: 14,
                            color: "#333"
                        }}>新品</Text>
                    </View>
                </TouchableOpacity>
                <TouchableOpacity
                    onPress={() => this.selectCate(2)}
                    style={{flex: 1, alignItems: 'center', justifyContent: 'center', height: 40}}>
                    <View style={[{
                        alignItems: 'center',
                        justifyContent: 'center',
                        height: 40
                    }, this.state.cate_index == 2 ? {
                        borderBottomWidth: 1,
                        borderBottomColor: "#ee1f12"
                    } : {borderBottomWidth: 2, borderBottomColor: "transparent"}]}>
                        <Text style={this.state.cate_index == 2 ? {fontSize: 14, color: "#ee1f12"} : {
                            fontSize: 14,
                            color: "#333"
                        }}>主推</Text>
                    </View>
                </TouchableOpacity>
                <TouchableOpacity
                    onPress={() => this.selectCate(3)}
                    style={{flex: 1, alignItems: 'center', justifyContent: 'center', height: 40}}>
                    <View style={[{
                        alignItems: 'center',
                        justifyContent: 'center',
                        height: 40
                    }, this.state.cate_index == 3 ? {
                        borderBottomWidth: 1,
                        borderBottomColor: "#ee1f12"
                    } : {borderBottomWidth: 2, borderBottomColor: "transparent"}]}>
                        <Text style={this.state.cate_index == 3 ? {fontSize: 14, color: "#ee1f12"} : {
                            fontSize: 14,
                            color: "#333"
                        }}>促销</Text>
                    </View>
                </TouchableOpacity>
                <TouchableOpacity
                    onPress={() => this.selectCate(4)}
                    style={[{flex: 1, alignItems: 'center', justifyContent: 'center', height: 40}]}>
                    <View style={[{
                        alignItems: 'center',
                        justifyContent: 'center',
                        height: 40
                    }, this.state.cate_index == 4 ? {
                        borderBottomWidth: 1,
                        borderBottomColor: "#ee1f12"
                    } : {borderBottomWidth: 2, borderBottomColor: "transparent"}]}>
                        <Text style={this.state.cate_index == 4 ? {fontSize: 14, color: "#ee1f12"} : {
                            fontSize: 14,
                            color: "#333"
                        }}>拼团</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }


    toGoodsIndex(goods_id) {
        let isLogin = this.state.isLogin
        if (isLogin) {
            this.props.navigation.push('GoodsIndex',{
                goods_id:goods_id
            })
        } else {
            this.toLogin()
        }
    }


    toLogin() {
        this.props.navigation.push('Login', {
            isPop: 1,
            callback: ()=>{
                this.getIndexAgain()
            }
        })
    }




    toGroupGoodsIndex(id, goods_id) {
        let isLogin = this.state.isLogin
        if (isLogin) {
            this.props.navigation.push('GroupGoodsIndex',{
                pin_id:id,
                goods_id:goods_id
            })
        } else {
           this.toLogin()
        }
    }


    _onRefresh() {
        this.setState({
            isRefreshing: true,
            loadedGoods: false,
        })
        this.getindex()
    }


    showHeaderSearch() {
        return (
            <View style={{
                flex: 1,
                marginHorizontal: 5,
                height: 28,
                backgroundColor: "#ccc",
                borderRadius: 5,
                paddingHorizontal: 10,
                flexDirection: 'row',
                alignItems: 'center'
            }}>
                <Image
                    source={require('../imgs/jy_search.png')}
                    resizeMode={'cover'}
                    style={{width: 15, height: 15, marginRight: 10}}
                />
                <TextInput
                    placeholder='搜索商品/货号'
                    underlineColorAndroid={'transparent'}
                    placeholderTextColor={'#fff'}
                    style={{flex: 1, fontSize: 12, color: "#fff", padding: 0}}
                    onChangeText={(txt) => this.setState({searchTxt: txt})}
                    onSubmitEditing={() => this.toSearch()}
                />
            </View>
        )
    }

    toSearch() {
        let searchTxt = this.state.searchTxt
        if (!searchTxt) {
            Toast.show('请输入搜索内容')
        }
        this.props.navigation.push('GoodsList',{
            isSearch:true,
            title:searchTxt
        })

    }

    toNews() {
        this.props.navigation.push('News')
    }

    async getIndexAgain() {
        await this.getUser()
        this.setState({
            loadedGoods: false,
            loaded: false
        })
        this.getindex()
    }

    indexHeader() {
        return (
            <View>
                <View style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    height: 50,
                    backgroundColor: "#fff",
                    paddingHorizontal: 10
                }}>
                    <TouchableOpacity onPress={() => this.getIndexAgain()}>
                        <Image
                            source={require('../imgs/jy_logo.jpg')}
                            resizeMode={'cover'}
                            style={{width: 90, height: 27.5}}
                        />
                    </TouchableOpacity>
                    {this.showHeaderSearch()}
                    <TouchableOpacity onPress={() => this.toNews()}>
                        <Image
                            source={require('../imgs/jy_msg.jpg')}
                            resizeMode={'cover'}
                            style={{width: 20, height: 20, marginLeft: 5}}
                        />
                    </TouchableOpacity>
                </View>
            </View>
        )
    }

    render() {
        return (
            <View style={{flex: 1}}>
                {this.indexHeader()}
                {!this.state.loaded ?
                    <View style={{flex: 1}}>
                        {Util.loading()}
                    </View>
                    :
                    <ScrollView style={{flex: 1, backgroundColor: "#fff"}}
                                refreshControl={
                                    <RefreshControl
                                        refreshing={this.state.isRefreshing}
                                        onRefresh={this._onRefresh.bind(this)}
                                        tintColor="#ff0000"
                                        title="Loading..."
                                        titleColor="#00ff00"
                                        colors={['#ff0000', '#00ff00', '#0000ff']}
                                        progressBackgroundColor="#ffff00"
                                    />
                                }
                    >
                        {this.topHeader()}
                    </ScrollView>
                }


            </View>
        )
    }
}